package com.bwie.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: ykk
 * @create: 2024-10-08 09:09
 **/
@Configuration
public class WhiteList implements GlobalFilter, Ordered {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String[] baiList=new String[]{"/user/login"};
        String s = request.getPath().toString();
        for (int i = 0; i < baiList.length; i++) {
            if(s.contains(baiList[i])){
                return chain.filter(exchange);
            }
        }
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }else{
            Claims body = Jwts.parser().setSigningKey("123456")
                    .parseClaimsJws(token).getBody();
            Integer id = body.get("id", Integer.class);
            String tokenRedis = stringRedisTemplate.opsForValue().get("token:" + id);
            if(!token.equals(tokenRedis)){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }else{
                Long expire = stringRedisTemplate.getExpire("token:" + id, TimeUnit.MINUTES);
                if(expire<10){
                    stringRedisTemplate.opsForValue().set("token:"+id,token,15,TimeUnit.MINUTES);
                }
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
